<template>
	<view>
		<van-calendar ref="calendar" :show="showDatetime" type="range" :min-date="minDate" id="myCalendar"
			:default-date="defaultDate" :max-date="maxDate" @close.native="closeCalendar" :allow-same-day="allowSameDay">
			<view class="btn-group flex-between-row" slot="footer">
				<button class="calendar-button background-DADADA color-666666 font-size-24" @click="reset">重置</button>
				<button class="calendar-button background-DC9F2D color-FFFFFF font-size-24"
					@click="confirmDate">完成</button>
			</view>
		</van-calendar>
	</view>
</template>
<script>
	import moment from 'moment'
	export default {
		name: "calendar",
		props: {
			showDatetime: {
				type: Boolean,
				default: false
			},
			minDate: {
				type: Number,
				default: new Date().getTime() - 1000 * 60 * 60 * 24 * 180
			},
			maxDate: {
				type: Number,
				default: new Date().getTime() + 1000 * 60 * 60 * 24 * 180
			},
			startTime: {
				type: String,
				default: ''
			},
			endTime: {
				type: String,
				default: ''
			},
			allowSameDay: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				defaultDate: null
			};
		},
		mounted() {
			if(this.startTime&&this.endTime){
				let startUnix = moment(this.startTime).format('x')
				let endUnix = moment(this.endTime).format('x')
				this.defaultDate = [Number(startUnix), Number(endUnix)]
			}else{
				this.defaultDate = [new Date().getTime()]
			}
		},
		methods: {
			closeCalendar() {
				this.$emit("update:showDatetime", false)
			},
			reset() {
				this.selectComponent('#myCalendar').reset()
				this.selectComponent('#myCalendar').data.defaultDate = null
				this.$emit("reset")
			},
			confirmDate() {
				let date = this.$refs.calendar.data.currentDate
				if (date[0] == date[1]) {
					this.$tip.toast("范围不能为同一天")
					return
				}
				if (!date[0] || !date[1]) {
					this.$tip.toast("请选择完整时间范围")
					return
				}
				let startTime = moment(date[0]).format("YYYY-MM-DD")
				let endTime = moment(date[1]).format("YYYY-MM-DD")
				this.$emit("confirmDate", startTime, endTime)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.calendar-button {
		margin: 0;
		flex: 0 0 40%;
		height: 64rpx;
		line-height: 64rpx;
	}

	.btn-group {
		padding-bottom: 30rpx;
	}
</style>
